package com.leyou.order.task;

import com.leyou.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class ScheduleTask {
    /**
     * 定时任务的执行周期
     */
    private static final long EVICT_PERIOD_TIME = 10 * 60 * 1000;
    /**
     *  超时订单的超时时间
     */
    private static final long ORDER_OVERDUE_TIME = 60 * 60 * 1000;
    /**
     * 锁在redis中的key
     */
    private static final String LOCK_KEY = "order:evict:lock";

    private final OrderService orderService;
    private final RedissonClient redissonClient;
    public ScheduleTask(OrderService orderService, RedissonClient redissonClient) {
        this.orderService = orderService;
        this.redissonClient = redissonClient;
    }


    @Scheduled(fixedDelay = EVICT_PERIOD_TIME)
    public void evictOrder() {
        // 获取锁对象
        RLock lock = redissonClient.getLock(LOCK_KEY);
        // 尝试获取锁
        boolean isLock = lock.tryLock();
        // 判断
        if(!isLock){
            // 获取锁失败
            log.info("【清理订单任务】未能获取任务锁，结束任务。");
            return;
        }
        // 获取锁成功，执行任务
        try {
            orderService.evictOverdueOrder(new Date(System.currentTimeMillis() - ORDER_OVERDUE_TIME));
            log.info("【清理订单任务】任务执行完毕，订单清理结束！");
        }finally {
            // 释放锁
            log.info("【清理订单任务】释放锁。");
            lock.unlock();
        }
    }
}
